class Messenger {
  /**
   * target 目标：发送者或接收者
   * domain 域：如果是发送者，则是接收者的域，反之亦然
   * callback：接收消息回调(data, source)
   */
  constructor(target, domain, callback){
    this._target = target;
    this._domain = domain;
    this.onReceiveMessage = this._onReceive.bind(this);
    this._callback = callback;
    window.addEventListener('message', this.onReceiveMessage, false);
  }

  sendToTarget(data){
    if(this._target){
      this._target.postMessage(data, this._domain);
    }
  }

  sendBack(data){
    this._sentBackData = data;
  }

  _onReceive(event) {
    if (event.origin !== this._domain){
      return;
    }
    this._callback && this._callback(event.data, event.source);
    if(this._sentBackData){
      event.source.postMessage(this._sentBackData, event.origin);
    }
  }
}

export default Messenger